package com.luo.chengrui.module.crbpm.service.definition;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
import cn.iocoder.yudao.framework.flowable.core.util.FlowableUtils;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.google.common.annotations.VisibleForTesting;
import com.luo.chengrui.framework.sadatapermission.core.annotation.SaDataPermission;
import com.luo.chengrui.module.crbpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleCreateReqVO;
import com.luo.chengrui.module.crbpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleRespVO;
import com.luo.chengrui.module.crbpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleUpdateReqVO;
import com.luo.chengrui.module.crbpm.convert.definition.BpmTaskAssignRuleConvert;
import com.luo.chengrui.module.crbpm.dal.dataobject.definition.BpmTaskAssignRuleDO;
import com.luo.chengrui.module.crbpm.dal.dataobject.definition.BpmUserGroupDO;
import com.luo.chengrui.module.crbpm.dal.mysql.definition.BpmTaskAssignRuleMapper;
import com.luo.chengrui.module.crbpm.enums.DictTypeConstants;
import com.luo.chengrui.module.crbpm.enums.definition.BpmTaskAssignRuleTypeEnum;
import com.luo.chengrui.module.crbpm.framework.flowable.core.behavior.script.BpmTaskAssignScript;
import com.luo.chengrui.module.crbpm.service.definition.dto.BpmAssignRuleMatrix;
import com.luo.chengrui.module.sa.api.org.SaOrgApi;
import com.luo.chengrui.module.sa.api.org.SaOrgMatrixApi;
import com.luo.chengrui.module.sa.api.org.dto.OrgRespDTO;
import com.luo.chengrui.module.sa.enums.OrgKindEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.text.CharSequenceUtil.format;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
import static com.luo.chengrui.module.crbpm.enums.ErrorCodeConstants.*;
import static com.luo.chengrui.module.crbpm.enums.ErrorCodeConstants.TASK_ASSIGN_RULE_EXISTS;
import static com.luo.chengrui.module.crbpm.enums.ErrorCodeConstants.TASK_UPDATE_FAIL_NOT_MODEL;

/**
 * BPM 任务分配规则 Service 实现类
 */
@Service
@Validated
@Slf4j
public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {

    @Resource
    private BpmTaskAssignRuleMapper taskRuleMapper;
    @Resource
    @Lazy // 解决循环依赖
    private BpmModelService modelService;
    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessDefinitionService processDefinitionService;
    @Resource
    private BpmUserGroupService userGroupService;
    @Resource
    private RoleApi roleApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private PostApi postApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DictDataApi dictDataApi;
    @Resource
    private PermissionApi permissionApi;
    @Resource
    private SaOrgApi saOrgApi;
    @Resource
    private SaOrgMatrixApi saOrgMatrixApi;
    /**
     * 任务分配脚本
     */
    private Map<Long, BpmTaskAssignScript> scriptMap = Collections.emptyMap();

    @Resource
    public void setScripts(List<BpmTaskAssignScript> scripts) {
        this.scriptMap = convertMap(scripts, script -> script.getEnum().getId());
    }

    @Override
    public List<BpmTaskAssignRuleDO> getTaskAssignRuleListByProcessDefinitionId(String processDefinitionId,
                                                                                String taskDefinitionKey) {
        return taskRuleMapper.selectListByProcessDefinitionId(processDefinitionId, taskDefinitionKey);
    }

    @Override
    public List<BpmTaskAssignRuleDO> getTaskAssignRuleListByModelId(String modelId) {
        return taskRuleMapper.selectListByModelId(modelId);
    }

    @Override
    public List<BpmTaskAssignRuleRespVO> getTaskAssignRuleList(String modelId, String processDefinitionId) {
        // 获得规则
        List<BpmTaskAssignRuleDO> rules = Collections.emptyList();
        BpmnModel model = null;
        if (StrUtil.isNotEmpty(modelId)) {
            rules = getTaskAssignRuleListByModelId(modelId);
            model = modelService.getBpmnModel(modelId);
        } else if (StrUtil.isNotEmpty(processDefinitionId)) {
            rules = getTaskAssignRuleListByProcessDefinitionId(processDefinitionId, null);
            model = processDefinitionService.getBpmnModel(processDefinitionId);
        }
        if (model == null) {
            return Collections.emptyList();
        }

        // 获得用户任务，只有用户任务才可以设置分配规则
        List<UserTask> userTasks = FlowableUtils.getBpmnModelElements(model, UserTask.class);
        if (CollUtil.isEmpty(userTasks)) {
            return Collections.emptyList();
        }
        // 转换数据
        return BpmTaskAssignRuleConvert.INSTANCE.convertList(userTasks, rules);
    }

    @Override
    public List<BpmTaskAssignRuleRespVO> getTaskAssignRuleList(String modelId, String processDefinitionId, String orgId) {
        // 获得规则
        List<BpmTaskAssignRuleDO> rules = Collections.emptyList();
        List<BpmTaskAssignRuleDO> orgRules = Collections.emptyList();
        BpmnModel model = null;
        if (StrUtil.isNotEmpty(processDefinitionId)) {
            rules = getTaskAssignRuleListByProcessDefinitionId(processDefinitionId, null);
            orgRules = getTaskAssignRuleListByProcessDefinitionIdAndOrgId(processDefinitionId, orgId);
            model = processDefinitionService.getBpmnModel(processDefinitionId);
        } else if (StrUtil.isNotEmpty(modelId)) {
            rules = getTaskAssignRuleListByModelId(modelId);
            orgRules = getTaskAssignRuleListByModelIdAndOrgId(modelId, orgId);
            model = modelService.getBpmnModel(modelId);
        }
        if (model == null) {
            return Collections.emptyList();
        }

        rules = rules.stream().filter(item -> StrUtil.isEmpty(item.getOrgId())).collect(Collectors.toList());

        // 获得用户任务，只有用户任务才可以设置分配规则
        List<UserTask> userTasks = FlowableUtils.getBpmnModelElements(model, UserTask.class);
        if (CollUtil.isEmpty(userTasks)) {
            return Collections.emptyList();
        }
        // 转换数据
        List<BpmTaskAssignRuleRespVO> result = BpmTaskAssignRuleConvert.INSTANCE.convertList(userTasks, rules);
        List<BpmTaskAssignRuleRespVO> orgList = BpmTaskAssignRuleConvert.INSTANCE.convertList(userTasks, orgRules);
        result.addAll(orgList.stream().filter(item -> StrUtil.isNotEmpty(item.getOrgId())).collect(Collectors.toList()));
        return result;
    }

    private List<BpmTaskAssignRuleDO> getTaskAssignRuleListByModelIdAndOrgId(String modelId, String orgId) {

        return taskRuleMapper.getTaskAssignRuleListByModelIdAndOrgId(modelId, orgId);
    }

    private List<BpmTaskAssignRuleDO> getTaskAssignRuleListByProcessDefinitionIdAndOrgId(String processDefinitionId, String orgId) {
        return taskRuleMapper.getTaskAssignRuleListByProcessDefinitionIdAndOrgId(processDefinitionId, orgId);
    }

    @Override
    public Long createTaskAssignRule(@Valid BpmTaskAssignRuleCreateReqVO reqVO) {
        // 校验参数
        validTaskAssignRuleOptions(reqVO.getType(), reqVO.getOptions());

        if (StrUtil.isEmpty(reqVO.getOrgId())) {
            // 校验是否已经配置
            BpmTaskAssignRuleDO existRule =
                    taskRuleMapper.selectListByModelIdAndTaskDefinitionKey(reqVO.getModelId(), reqVO.getTaskDefinitionKey());
            if (existRule != null) {
                throw exception(TASK_ASSIGN_RULE_EXISTS, reqVO.getModelId(), reqVO.getTaskDefinitionKey());
            }
            // 存储
            BpmTaskAssignRuleDO rule = BpmTaskAssignRuleConvert.INSTANCE.convert(reqVO)
                    .setProcessDefinitionId(BpmTaskAssignRuleDO.PROCESS_DEFINITION_ID_NULL); // 只有流程模型，才允许新建
            rule.setOrgId(BpmTaskAssignRuleDO.PROCESS_DEFINITION_ID_NULL);
            taskRuleMapper.insert(rule);
            return rule.getId();
        } else {
            BpmTaskAssignRuleDO existRule =
                    taskRuleMapper.selectOrgRuleListByProcessDefinitionIdAndTaskDefinitionKey(reqVO.getProcessDefinitionId(), reqVO.getTaskDefinitionKey(), reqVO.getOrgId());
            if (existRule != null) {
                throw exception(TASK_ASSIGN_RULE_EXISTS, reqVO.getModelId(), reqVO.getTaskDefinitionKey());
            }
            BpmTaskAssignRuleDO rule = BpmTaskAssignRuleConvert.INSTANCE.convert(reqVO);
            taskRuleMapper.insert(rule);
            return rule.getId();
        }

    }

    @Override
    public void updateTaskAssignRule(@Valid BpmTaskAssignRuleUpdateReqVO reqVO) {
        // 校验参数
        validTaskAssignRuleOptions(reqVO.getType(), reqVO.getOptions());
        // 校验是否存在
        BpmTaskAssignRuleDO existRule = taskRuleMapper.selectById(reqVO.getId());
        if (existRule == null) {
            throw exception(TASK_ASSIGN_RULE_NOT_EXISTS);
        }

        if (StrUtil.isEmpty(reqVO.getOrgId())) {
            // 只允许修改流程模型的规则
            if (!Objects.equals(BpmTaskAssignRuleDO.PROCESS_DEFINITION_ID_NULL, existRule.getProcessDefinitionId())) {
                throw exception(TASK_UPDATE_FAIL_NOT_MODEL);
            }
        }

        // 执行更新
        taskRuleMapper.updateById(BpmTaskAssignRuleConvert.INSTANCE.convert(reqVO));
    }

    @Override
    public boolean isTaskAssignRulesEquals(String modelId, String processDefinitionId) {
        // 调用 VO 接口的原因是，过滤掉流程模型不需要的规则，保持和 copyTaskAssignRules 方法的一致性
        List<BpmTaskAssignRuleRespVO> modelRules = getTaskAssignRuleList(modelId, null);
        List<BpmTaskAssignRuleRespVO> processInstanceRules = getTaskAssignRuleList(null, processDefinitionId);
        if (modelRules.size() != processInstanceRules.size()) {
            return false;
        }

        // 遍历，匹配对应的规则
        Map<String, BpmTaskAssignRuleRespVO> processInstanceRuleMap =
                CollectionUtils.convertMap(processInstanceRules, BpmTaskAssignRuleRespVO::getTaskDefinitionKey);
        for (BpmTaskAssignRuleRespVO modelRule : modelRules) {
            BpmTaskAssignRuleRespVO processInstanceRule = processInstanceRuleMap.get(modelRule.getTaskDefinitionKey());
            if (processInstanceRule == null) {
                return false;
            }
            if (!ObjectUtil.equals(modelRule.getType(), processInstanceRule.getType()) || !ObjectUtil.equal(
                    modelRule.getOptions(), processInstanceRule.getOptions())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void copyTaskAssignRules(String fromModelId, String toProcessDefinitionId) {
        List<BpmTaskAssignRuleRespVO> rules = getTaskAssignRuleList(fromModelId, null);
        if (CollUtil.isEmpty(rules)) {
            return;
        }
        // 开始复制
        List<BpmTaskAssignRuleDO> newRules = BpmTaskAssignRuleConvert.INSTANCE.convertList2(rules);
        newRules.forEach(rule -> rule.setProcessDefinitionId(toProcessDefinitionId).setId(null).setCreateTime(null)
                .setUpdateTime(null));
        taskRuleMapper.insertBatch(newRules);
    }

    @Override
    public void checkTaskAssignRuleAllConfig(String id) {
        // 一个用户任务都没配置，所以无需配置规则
        List<BpmTaskAssignRuleRespVO> taskAssignRules = getTaskAssignRuleList(id, null);
        if (CollUtil.isEmpty(taskAssignRules)) {
            return;
        }
        // 校验未配置规则的任务
        taskAssignRules.forEach(rule -> {
            if (Objects.equals(rule.getType(), BpmTaskAssignRuleTypeEnum.MATRIX.getType())) {
                //诚睿 流程引擎规则时，数据类型不同，需单独处理

            } else {
                // ruoyi 流程引擎规则，
                if (CollUtil.isEmpty(convertTo(rule.getOptions(), ","))) {
                    throw exception(MODEL_DEPLOY_FAIL_TASK_ASSIGN_RULE_NOT_CONFIG, rule.getTaskDefinitionName());
                }
            }
        });
    }

    private void validTaskAssignRuleOptions(Integer type, String options) {
        if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.ROLE.getType())) {

            roleApi.validRoleList(convertTo(options, ","));
        } else if (ObjectUtils.equalsAny(type, BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(),
                BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType())) {
            deptApi.validateDeptList(convertTo(options, ","));
        } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) {
            postApi.validPostList(convertTo(options, ","));
        } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) {
            adminUserApi.validateUserList(convertTo(options, ","));
        } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) {
            userGroupService.validUserGroups(convertTo(options, ","));
        } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) {
            dictDataApi.validateDictDataList(DictTypeConstants.TASK_ASSIGN_SCRIPT,
                    CollectionUtils.convertSet(convertTo(options, ","), String::valueOf));
        } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.MATRIX.getType())) {
            // TODO 校验矩阵配置是否正确
        } else {
            throw new IllegalArgumentException(format("未知的规则类型({})", type));
        }
    }

    @Override
    @SaDataPermission(enable = false) // 忽略数据权限，不然分配会存在问题
    public Set<Long> calculateTaskCandidateUsers(DelegateExecution execution) {
        BpmTaskAssignRuleDO rule = getTaskRule(execution);
        return calculateTaskCandidateUsers(execution, rule);
    }

    @VisibleForTesting
    BpmTaskAssignRuleDO getTaskRule(DelegateExecution execution) {
        List<BpmTaskAssignRuleDO> taskRules = Collections.emptyList();
        if (StrUtil.isNotEmpty(String.valueOf(execution.getVariables().get("orgDefinitionOrgId")))) {
            // 先获取组织机构 的审批规则
            taskRules = getTaskAssignRuleListByProcessDefinitionIdAndOrgIdAndActivityId(
                    execution.getProcessDefinitionId(), String.valueOf(execution.getVariables().get("orgDefinitionOrgId")), execution.getCurrentActivityId());
        }
        if (CollUtil.isEmpty(taskRules)) {
            // 没有组织规则，则获取全局规则
            taskRules = getTaskAssignRuleListByProcessDefinitionId(
                    execution.getProcessDefinitionId(), execution.getCurrentActivityId());
        }
        if (CollUtil.isEmpty(taskRules)) {
            throw new FlowableException(format("流程任务({}/{}/{}) 找不到符合的任务规则",
                    execution.getId(), execution.getProcessDefinitionId(), execution.getCurrentActivityId()));
        }
        if (taskRules.size() > 1) {
            throw new FlowableException(format("流程任务({}/{}/{}) 找到过多任务规则({})",
                    execution.getId(), execution.getProcessDefinitionId(), execution.getCurrentActivityId()));
        }
        return taskRules.get(0);
    }

    private List<BpmTaskAssignRuleDO> getTaskAssignRuleListByProcessDefinitionIdAndOrgIdAndActivityId(String processDefinitionId, String orgId, String taskDefinitionKey) {
        return taskRuleMapper.getTaskAssignRuleListByProcessDefinitionIdAndOrgIdAndActivityId(processDefinitionId, orgId, taskDefinitionKey);
    }

    /**
     * 计算审批人
     *
     * @param execution
     * @param rule
     * @return
     */
    @VisibleForTesting
    Set<Long> calculateTaskCandidateUsers(DelegateExecution execution, BpmTaskAssignRuleDO rule) {
        Set<Long> assigneeUserIds = null;
        if (Objects.equals(BpmTaskAssignRuleTypeEnum.ROLE.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByRole(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByDeptMember(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByDeptLeader(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.POST.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByPost(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.USER.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByUser(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.USER_GROUP.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByUserGroup(rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.SCRIPT.getType(), rule.getType())) {
            assigneeUserIds = calculateTaskCandidateUsersByScript(execution, rule);
        } else if (Objects.equals(BpmTaskAssignRuleTypeEnum.MATRIX.getType(), rule.getType())) {
            //审批规则为 矩阵
            assigneeUserIds = calculateTaskCandidateUsersByMatrix(execution, rule);
        }

        // 移除被禁用的用户
        removeDisableUsers(assigneeUserIds);
        // 如果候选人为空，抛出异常
        if (CollUtil.isEmpty(assigneeUserIds)) {
            log.error("[calculateTaskCandidateUsers][流程任务({}/{}/{}) 任务规则({}) 找不到候选人]", execution.getId(),
                    execution.getProcessDefinitionId(), execution.getCurrentActivityId(), toJsonString(rule));
            throw exception(TASK_CREATE_FAIL_NO_CANDIDATE_USER);
        }
        return assigneeUserIds;
    }


    private Set<Long> convertTo(String ids, String sper) {
        if (StrUtil.isNotEmpty(ids)) {
            String[] roles = ids.split(sper);
            return Arrays.stream(roles).map(r -> Long.valueOf(r)).collect(Collectors.toSet());
        }
        return null;
    }

    private Set<Long> calculateTaskCandidateUsersByRole(BpmTaskAssignRuleDO rule) {
        String[] roles = rule.getOptions().split(",");
        Set<Long> roleIds = Arrays.stream(roles).map(r -> Long.valueOf(r)).collect(Collectors.toSet());
        return permissionApi.getUserRoleIdListByRoleIds(roleIds).getCheckedData();
    }


    private Set<Long> calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) {
        List<AdminUserRespDTO> users = adminUserApi.getUserListByDeptIds(convertTo(rule.getOptions(), ",")).getCheckedData();
        return convertSet(users, AdminUserRespDTO::getId);
    }

    private Set<Long> calculateTaskCandidateUsersByDeptLeader(BpmTaskAssignRuleDO rule) {
        List<DeptRespDTO> depts = deptApi.getDeptList(convertTo(rule.getOptions(), ",")).getCheckedData();
        return convertSet(depts, DeptRespDTO::getLeaderUserId);
    }

    private Set<Long> calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) {
        List<AdminUserRespDTO> users = adminUserApi.getUserListByPostIds(convertTo(rule.getOptions(), ",")).getCheckedData();
        return convertSet(users, AdminUserRespDTO::getId);
    }

    private Set<Long> calculateTaskCandidateUsersByUser(BpmTaskAssignRuleDO rule) {
        return convertTo(rule.getOptions(), ",");
    }

    private Set<Long> calculateTaskCandidateUsersByUserGroup(BpmTaskAssignRuleDO rule) {
        List<BpmUserGroupDO> userGroups = userGroupService.getUserGroupList(convertTo(rule.getOptions(), ","));
        Set<Long> userIds = new HashSet<>();
        userGroups.forEach(group -> userIds.addAll(group.getMemberUserIds()));
        return userIds;
    }

    private Set<Long> calculateTaskCandidateUsersByScript(DelegateExecution execution, BpmTaskAssignRuleDO rule) {
        // 获得对应的脚本
        Set<Long> ids = convertTo(rule.getOptions(), ",");
        List<BpmTaskAssignScript> scripts = new ArrayList<>(ids.size());
        ids.forEach(id -> {
            BpmTaskAssignScript script = scriptMap.get(id);
            if (script == null) {
                throw exception(TASK_ASSIGN_SCRIPT_NOT_EXISTS, id);
            }
            scripts.add(script);
        });
        // 逐个计算任务
        Set<Long> userIds = new HashSet<>();
        scripts.forEach(script -> CollUtil.addAll(userIds, script.calculateTaskCandidateUsers(execution)));
        return userIds;
    }

    /**
     * 解析矩阵人员
     *
     * @param execution
     * @param rule
     * @return
     */
    private Set<Long> calculateTaskCandidateUsersByMatrix(DelegateExecution execution, BpmTaskAssignRuleDO rule) {
        JSONArray jsonArray = new JSONArray(rule.getOptions());
        List<BpmAssignRuleMatrix> list = new ArrayList<>();
        jsonArray.jsonIter().forEach(item -> {
            BpmAssignRuleMatrix matrix = new BpmAssignRuleMatrix();
            matrix.setId(item.get("id", String.class));
            matrix.setOrgKindId(item.get("orgKindId", String.class));
            matrix.setName(item.get("name", String.class));
            matrix.setFullName(item.get("fullName", String.class));
            list.add(matrix);
        });
        List<OrgRespDTO> orgList = new ArrayList<>();
        list.forEach(item -> {

            switch (OrgKindEnum.getByCode(item.getOrgKindId())) {
                case Org:
                    // 机构
                case Center:
                    // 中心
                case Dept:
                    // 部门
                case Position:
                    // 岗位
                case Psm:
                    // 人员
                    List<OrgRespDTO> itemList = saOrgApi.getAllPersonMemberListByOrgId(item.getId()).getCheckedData();
                    if (CollUtil.isNotEmpty(itemList)) {
                        orgList.addAll(itemList);
                    }
                    break;

                case OrgMatrix:
                    // 组织矩阵
                    String[] orgAndDefindId = item.getId().split("_@_");
                    List<OrgRespDTO> martrixItemList = saOrgMatrixApi.getOrgManagerMatrixPerson(orgAndDefindId[0], orgAndDefindId[1]).getCheckedData();
                    if (CollUtil.isNotEmpty(martrixItemList)) {
                        orgList.addAll(martrixItemList);
                    }
                    break;
                case bizMatrix:
                    // 业务矩阵
                    List<OrgRespDTO> bizMatrixItemList = saOrgMatrixApi.getBizManagerMatrixPerson(item.getId()).getCheckedData();
                    if (CollUtil.isNotEmpty(bizMatrixItemList)) {
                        orgList.addAll(bizMatrixItemList);
                    }
                    break;

            }

        });
        if (CollUtil.isNotEmpty(orgList)) {
            return orgList.stream().map(item -> item.getSystemId()).collect(Collectors.toSet());
        }
        return null;
    }

    @VisibleForTesting
    void removeDisableUsers(Set<Long> assigneeUserIds) {
        if (CollUtil.isEmpty(assigneeUserIds)) {
            return;
        }
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(assigneeUserIds);
        assigneeUserIds.removeIf(id -> {
            AdminUserRespDTO user = userMap.get(id);
            return user == null || !CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus());
        });
    }

}
